package
{
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.*;
	import flash.external.ExternalInterface;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;

	public class StateLoading extends State
	{
		[Embed(source="Loading.swf")]
		public var Loading:Class;
		protected var movieclip:MovieClip = new Loading();
		
		protected var objects:Array;
		protected var exResource:Vector.<ExternalResource>;
		protected var loader:URLLoader;
		protected var converter:Loader;
		protected var count:uint;
		protected var loadedBytes:String = "";
		protected var loadedFiles:String = "";
		protected var parent:State = null;
		protected var transparent:Boolean;
		public function StateLoading(exResource:Vector.<ExternalResource>, objects:Array, parent:State, trans:Boolean = false)
		{
			super();
			this.exResource = exResource;
			this.objects = objects;
			this.parent = parent;
			this.transparent = trans;
			loader = new URLLoader();
			loader.dataFormat = URLLoaderDataFormat.BINARY;
			configureListeners(loader);
			//loader.addEventListener(MouseEvent.CLICK, clickHandler);
			count = 0;
			for(var i:uint = count;i<exResource.length;i++)
			{
				if(exResource[i].GetData() != null)
				{
					objects.push(exResource[i].GetData());
					count++;
				}
			}
			if(count < exResource.length)
			{
				loader = new URLLoader();
				loader.dataFormat = URLLoaderDataFormat.BINARY;
				configureListeners(loader);
				//loader.addEventListener(MouseEvent.CLICK, clickHandler);
				var request:URLRequest = new URLRequest(exResource[count].GetPath());
				loader.load(request);
			}
			else
			{
				//FBGame.stateStack.Pop();
				//parent.LoadComplete(true);
				BeginConvert();
				loadedBytes = "Load all finish";
			}
			//parent.addChild(loader);

		}
		private function configureListeners(dispatcher:IEventDispatcher):void {
			dispatcher.addEventListener(Event.COMPLETE, completeHandler);
			dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
			//dispatcher.addEventListener(Event.INIT, initHandler);
			dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			//dispatcher.addEventListener(Event.OPEN, openHandler);
			dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			//dispatcher.addEventListener(Event.UNLOAD, unLoadHandler);
		}
		private function configureListenersConverter(dispatcher:IEventDispatcher):void {
			dispatcher.addEventListener(Event.COMPLETE, completeHandlerConverter);
			dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
			//dispatcher.addEventListener(Event.INIT, initHandler);
			dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			//dispatcher.addEventListener(Event.OPEN, openHandler);
			dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			//dispatcher.addEventListener(Event.UNLOAD, unLoadHandler);
		}
		private function completeHandler(event:Event):void {
			//trace("completeHandler: " + event);
			//var object:Object = event.currentTarget.content;
			var loader2:URLLoader = URLLoader(event.target);
			var object:ByteArray = loader2.data;
			/*
			if(object != null && exResource[count].GetType() == ExternalResource.movieClip)
			{
				try
				{
					object.SetContainer(FBGame.mainFBGame);
				}
				catch(e:Error)
				{
					if(FBGame.debug == false)
					{
						FBGame.stateStack.Pop();
						parent.LoadComplete(false);
						
						return;
					}
				}
			}
			*/
			objects.push(object);
			count++;
			loadedBytes = count.toString() + " files";
			for(var i:uint = count;i<exResource.length;i++)
			{
				if(exResource[i].GetData() != null)
				{
					objects.push(exResource[i].GetData());
					count++;
				}
			}
			if(count < exResource.length)
			{
				loader = new URLLoader();
				loader.dataFormat = URLLoaderDataFormat.BINARY;
				configureListeners(loader);
				//loader.addEventListener(MouseEvent.CLICK, clickHandler);
				var request:URLRequest = new URLRequest(exResource[count].GetPath());
				loader.load(request);
			}
			else
			{
				//FBGame.stateStack.Pop();
				//parent.LoadComplete(true);
				BeginConvert();
				loadedBytes = "Load all finish";
			}
		}
		
		private function httpStatusHandler(event:HTTPStatusEvent):void {
			//trace("httpStatusHandler: " + event);
			loadedBytes = "httpStatusHandler " + event;
		}
		
		private function initHandler(event:Event):void {
			trace("initHandler: " + event);
		}
		
		private function ioErrorHandler(event:IOErrorEvent):void {
			trace("ioErrorHandler: " + event);
			loadedBytes = "IO error " + event.text;
			if(FBGame.debug == true)
			{
				
			}
			else
			{
				FBGame.stateStack.Pop();
				parent.LoadComplete(false);
				
			}
			//FBGame.stateStack.Pop();
		}
		
		private function openHandler(event:Event):void {
			trace("openHandler: " + event);
		}
		
		private function progressHandler(event:ProgressEvent):void {
			trace("progressHandler: bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal);
			loadedBytes = event.bytesLoaded.toString() + " bytes";
		}
		
		private function unLoadHandler(event:Event):void {
			trace("unLoadHandler: " + event);
		}
		
		private function clickHandler(event:MouseEvent):void {
			trace("clickHandler: " + event);
			//var loader:Loader = Loader(event.target);
			//loader.unload();
		}
		public override function Render(g:MyGraphics):void
		{
			if(this.transparent == false)
			{
				if(FBGame.debug)
				{
					g.Clear(0xFFFFFFFF);
					g.DrawString("Loading.....",10,10,0xFFFF0000);
					g.DrawString(loadedFiles,10,50,0xFF000000);
					g.DrawString(loadedBytes,10,100,0xFF000000);
				}
				else
				{
					g.Clear(0xFF000000);
					g.DrawMovieClip(0,0,movieclip);
				}
			}
			else
			{
				if(this.stateIndex - 1 >= 0)
					FBGame.stateStack.GetStateAt(this.stateIndex - 1).Render(g);
			}
		}
		public override function Release():void
		{
			try
			{
				loader.close();
			}
			catch(ex:Error)
			{
				
			}
		}
		public function BeginConvert():void
		{
			converter = new Loader();
			configureListenersConverter(converter.contentLoaderInfo);
			count = 0;
			for(var i:uint = count;i<exResource.length;i++)
			{
				if(exResource[i].GetType() == ExternalResource.byteArray)
				{
					count++;
				}
			}
			if(count == exResource.length)
			{
				FBGame.stateStack.Pop();
				parent.LoadComplete(true);
				return;
			}
			var request:URLRequest = new URLRequest(exResource[count].GetPath());
			converter.loadBytes(objects[count]);
		}
		private function completeHandlerConverter(event:Event):void 
		{
			var object:Object = event.currentTarget.content;
			if(object != null && exResource[count].GetType() == ExternalResource.movieClip)
			{
				try
				{
					object.SetContainer(FBGame.mainFBGame);
				}
				catch(e:Error)
				{
					if(FBGame.debug == false)
					{
						FBGame.stateStack.Pop();
						parent.LoadComplete(false);
						
						return;
					}
				}
			}
			objects[count] = object;
			count++;
			for(var i:uint = count;i<exResource.length;i++)
			{
				if(exResource[i].GetType() == ExternalResource.byteArray)
				{
					count++;
				}
			}
			if(count == exResource.length)
			{
				FBGame.stateStack.Pop();
				parent.LoadComplete(true);
				return;
			}
			var request:URLRequest = new URLRequest(exResource[count].GetPath());
			converter.loadBytes(objects[count]);
		}
	}
}